{% extends 'base.html' %} 
{% block title %} 上传页面 {% endblock %} 
{% block content %}
<form
  class="layui-form"
  method="post"
  enctype="multipart/form-data"
>
  {% csrf_token %}
  <div class="layui-form-item">
    <label class="layui-form-label">姓名</label>
    <div class="layui-input-block">
      <input
        type="text"
        name="name"
        required
        lay-verify="required"
        placeholder="请输入姓名"
        autocomplete="off"
        class="layui-input"
        id="name"
      />
    </div>
  </div>
  <div class="layui-form-item">
    <label class="layui-form-label">联系地址</label>
    <div class="layui-input-block">
      <textarea
        name="address"
        placeholder="请输入联系地址"
        class="layui-textarea"
        id="address"
      ></textarea>
    </div>
  </div>
  <div class="layui-form-item">
    <div class="layui-input-block">
      <button class="layui-btn" lay-submit lay-filter="formDemo">
        立即上传
      </button>
    </div>
  </div>
</form>

<div class="layui-upload-drag" id="test10" style="margin-top: 20px">
  <i class="layui-icon"></i>
  <p>或者，拖拽文件到这里上传</p>
</div>
{% endblock %} 
{% block js %}
<script>
  layui.use(["form", "upload","jquery"], function () {
    var form = layui.form;
    var upload = layui.upload;
    var $ = layui.jquery;

    //拖拽上传
    var uploadDrag = upload.render({
      elem: "#test10",
      url: "/upload/",
    //   auto: false,
      before: function (obj) {
        this.data = {
            name: $('#name').val(),
            address: $('#address').val(),
            // isForceUpdate: $('#isForce input[name="force"]:checked ').val()
        };
        obj.preview(function (index, file, result) {
          console.log(file.size);
          if (file.size > 5 * 1024 * 1024) {
            // 5MB
            layer.msg("文件大小不能超过5MB");
            return false; // 阻止上传
          }
          // 检查文件扩展名
          var ext = file.name.split(".").pop().toLowerCase();
          if (["doc", "jpeg", "png"].indexOf(ext) === -1) {
            layer.msg("只允许上传.doc格式的文件");
            return false; // 阻止上传
          }
        });
      },
      done: function (res) {
        //如果上传失败
        if (res.code > 0) {
          return layer.msg("上传失败");
        }

        //上传成功
        layer.msg("上传成功");
        // 这里可以处理上传成功后的逻辑，例如显示上传的文件列表或跳转到其他页面等
        // 注意：这里的res.url是Django视图返回的文件的URL
      },
      error: function () {
        //演示失败状态，并实现重传
        var demoText = $("#test10");
        demoText.html(
          '<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini test-upload-reload">重试</a>'
        );
        demoText.find(".test-upload-reload").on("click", function () {
          uploadDrag.upload();
        });
      },
    });

    //监听提交
    form.on("submit(formDemo)", function (data) {
        console.log("提交了")
      // 执行提交
      return false; // 阻止表单跳转。如果需要表单跳转，去掉这段即可
    });
  });
</script>
{% endblock %}
